package com.curluin.inputInterpretation;

import com.curluin.controll.Controller;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.util.Log;

public class SpinInterpreter implements SensorEventListener{
	
	public static final String LOG_TAG="SpinInterpreter";
	
	Controller controller;
	SensorManager sensorManager;
	Sensor gyroSensor;
	SpinEvent spinEvent;
	// 'jumpThreshold' gegrees per second is the threshold of the angular speed to evoke a jump
	static final float jumpThreshold = 90; 

	public SpinInterpreter(Context context) {
		
		controller = (Controller) context;
		sensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
		
		// If there is a gyroscope available it is saved in gyroSensor
		if((gyroSensor = sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE)) == null)
			Log.e(LOG_TAG, "No Gyroscope available!");
		else{
			Log.i(LOG_TAG, "Gyroscope time resolution: "+gyroSensor.getMinDelay());
			sensorManager.registerListener(this, gyroSensor, SensorManager.SENSOR_DELAY_NORMAL);
			spinEvent = new SpinEvent();
		}
	}

	@Override
	public void onAccuracyChanged(Sensor sensor, int accuracy) {
		Log.w(LOG_TAG, "Gyroscope accuracy changed: "+accuracy);
	}

	@Override
	public void onSensorChanged(SensorEvent event) {
		if(controller==null) return;
		spinEvent.copyFrom(event);
		//Log.i(LOG_TAG, "Gyroscope sensed: "+spinEvent.angularSpeedAroundX);
		if(spinEvent.angularSpeedAroundX > jumpThreshold){
			controller.handleSpinEvent(Math.abs(spinEvent.angularSpeedAroundX));
			Log.i(LOG_TAG, "Gyroscope detected X-spin: "+spinEvent.angularSpeedAroundX);
		}
	}

	public void destroy() {;
		sensorManager.unregisterListener(this);
		sensorManager=null;
		gyroSensor=null;
		controller=null;
	}

}
